package beautiful.butterfly.distributed_task_processing_engine.task_manage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JvmInstanceIdStatusAndTaskManageInitThread extends Thread
{

    JvmInstanceStatusAndTaskManage jvmInstanceStatusAndTaskManage;
    volatile boolean isStop = false;

    public JvmInstanceIdStatusAndTaskManageInitThread(JvmInstanceStatusAndTaskManage jvmInstanceStatusAndTaskManage)
    {
        this.jvmInstanceStatusAndTaskManage = jvmInstanceStatusAndTaskManage;
    }

    public void stopThread()
    {
        this.isStop = true;
    }

    @Override
    public void run()
    {
        jvmInstanceStatusAndTaskManage.lock.lock();
        try
        {
            int count = 0;
            while (!jvmInstanceStatusAndTaskManage.zooKeeperManager.zooKeeperIsConnected())
            {
                count = count + 1;
                if (count % 50 == 0)
                {
                    jvmInstanceStatusAndTaskManage.errorMessage = "zooKeeper is connecting ......" + jvmInstanceStatusAndTaskManage.zooKeeperManager.getZooKeeperConnectString() + " spendTime:" + count * 20 + "(ms)";
                    log.error(jvmInstanceStatusAndTaskManage.errorMessage);
                }
                Thread.sleep(20);
                if (this.isStop == true)//快速停止 只是用于配置信息错误的情况
                {
                    return;
                }
            }
            //init
            jvmInstanceStatusAndTaskManage.doInit();
        } catch (Throwable e)
        {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally
        {
            jvmInstanceStatusAndTaskManage.lock.unlock();
        }

    }

}
